import type {
  LoadingConfig,
  AdaptiveConfig,
  PaginationProps
} from "@pureadmin/table";
import { ref, onMounted, reactive } from "vue";
import dayjs from "dayjs";
import type { Order } from "types/order";
import { getOrderPagination } from "@/api/order";
import FilterFlower from "./components/FilterFlower.vue";

export function useColumns(options: {
  onEdit?: (row: Order, index: number) => void;
}) {
  const dataList = ref<Order[]>([]);
  const loading = ref(true);
  const filter = reactive({
    order_status: 1,
    kw: undefined,
    presale: false,
    flower: []
  });
  const columns: TableColumnList = [
    {
      label: "订单号",
      prop: "order_code",
      width: 140,
      fixed: "left"
    },
    {
      label: "联系电话",
      prop: "customer_phone",
      width: 120,
      fixed: "left"
    },
    {
      label: "预售订单",
      prop: "presale",
      width: 140,
      headerRenderer: () => (
        <label
          class="flex items-center justify-center"
          style={{
            color: filter.presale
              ? "var(--el-color-primary)"
              : "var(--el-text-color-secondary)"
          }}
        >
          预售订单
          <el-checkbox
            class="ml-1"
            value={filter.presale}
            onChange={handlerFilterPresale}
          />
        </label>
      ),
      cellRenderer: ({ row }) => {
        if (row.presale) {
          return <el-tag type="primary">预售</el-tag>;
        }
      }
    },
    {
      label: "收货方式",
      prop: "delivery_method",
      width: 100,
      cellRenderer: ({ row }) => {
        switch (row.delivery_method) {
          case 1:
            return <el-tag type="primary">配送</el-tag>;
          case 2:
            return <el-tag type="info">自提</el-tag>;
          default:
            return <el-tag type="info">未知</el-tag>;
        }
      }
    },
    {
      label: "配送/自提时间",
      prop: "delivery_date",
      width: 160,
      cellRenderer: ({ row }) =>
        row.delivery_date ? (
          dayjs(row.delivery_date).format("YYYY-MM-DD HH:mm")
        ) : (
          <el-tag type="info">立即处理</el-tag>
        )
    },
    {
      label: "客户昵称",
      prop: "nickname",
      minWidth: 120,
      cellRenderer: ({ row }) => (row.customer ? row.customer.nickname : "")
    },
    {
      label: "下单时间",
      prop: "created_on",
      width: 160,
      cellRenderer: ({ row }) => (
        <span>{dayjs(row.created_on).format("YYYY-MM-DD HH:mm:ss")}</span>
      )
    },
    {
      label: "商品",
      prop: "product",
      width: 160,
      headerRenderer: () => {
        return (
          <FilterFlower
            modelValue={filter.flower}
            onUpdate:modelValue={handleFilterFlower}
          />
        );
      },
      cellRenderer: ({ row }) => {
        return (
          <div class="flex flex-col items-center gap-1">
            {row.items.map(item => (
              <el-tag key={item.id}>
                {item.flower.name + " x" + item.quantity}
              </el-tag>
            ))}
          </div>
        );
      }
    },
    {
      label: "支付状态",
      prop: "payment_status",
      width: 100,
      cellRenderer: ({ row }) => {
        switch (row.payment_status) {
          case 1:
            return <el-tag type="danger">待支付</el-tag>;
          case 2:
            return <el-tag type="success">已支付</el-tag>;
          case 3:
            return <el-tag type="warning">已退款</el-tag>;
          default:
            return <el-tag type="info">未知</el-tag>;
        }
      }
    },
    {
      label: "配送状态",
      prop: "shipping_status",
      width: 100,
      cellRenderer: ({ row }) => {
        switch (row.shipping_status) {
          case 1:
            return <el-tag type="danger">待发货</el-tag>;
          case 2:
            return <el-tag type="warning">配送中</el-tag>;
          case 3:
            return <el-tag type="success">已完成</el-tag>;
          default:
            return <el-tag type="info">未知</el-tag>;
        }
      }
    },
    {
      label: "订单状态",
      prop: "status",
      width: 100,
      cellRenderer: ({ row }) => {
        switch (row.status) {
          case 1:
            return <el-tag type="warning">进行中</el-tag>;
          case 2:
            return <el-tag type="success">已完成</el-tag>;
          case 3:
            return <el-tag type="info">已取消</el-tag>;
          default:
            return <el-tag type="info">未知</el-tag>;
        }
      }
    },
    {
      label: "操作",
      fixed: "right",
      cellRenderer: ({ index, row }) => (
        <el-button size="small" onClick={() => handleEdit(row, index)}>
          查看
        </el-button>
      )
    }
  ];

  /** 分页配置 */
  const pagination = reactive<PaginationProps>({
    pageSize: 20,
    currentPage: 1,
    pageSizes: [20, 40, 60],
    total: 60,
    align: "right",
    background: true,
    size: "default"
  });

  /** 加载动画配置 */
  const loadingConfig = reactive<LoadingConfig>({
    text: "正在加载第一页...",
    viewBox: "-10, -10, 50, 50",
    spinner: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
    // svg: "",
    // background: rgba()
  });

  /** 撑满内容区自适应高度相关配置 */
  const adaptiveConfig: AdaptiveConfig = {
    /** 表格距离页面底部的偏移量，默认值为 `96` */
    offsetBottom: 110
    /** 是否固定表头，默认值为 `true`（如果不想固定表头，fixHeader设置为false并且表格要设置table-layout="auto"） */
    // fixHeader: true
    /** 页面 `resize` 时的防抖时间，默认值为 `60` ms */
    // timeout: 60
    /** 表头的 `z-index`，默认值为 `100` */
    // zIndex: 100
  };

  interface RequestParams {
    page: number;
    page_size: number;
    kw?: string;
    order_status: number;
    presale?: boolean;
    flower?: string[];
  }

  async function loadData() {
    try {
      loading.value = true;
      const params: RequestParams = {
        page: pagination.currentPage,
        page_size: pagination.pageSize,
        order_status: filter.order_status
      };

      if (filter.kw && filter.kw.trim()) {
        params.kw = filter.kw.trim();
      }

      if (filter.presale) {
        params.presale = true;
      }

      if (filter.flower && filter.flower.length > 0) {
        params.flower = filter.flower;
      }

      const response = await getOrderPagination(params);

      pagination.total = response.total;
      dataList.value = response.data;
    } catch (e) {
      console.log(e);
    } finally {
      loading.value = false;
    }
  }

  async function onSizeChange() {
    pagination.currentPage = 1;

    loadData();
  }

  async function onCurrentChange() {
    loadingConfig.text = `正在加载第${pagination.currentPage}页...`;

    loadData();
  }

  async function handleEdit(row: Order, index: number) {
    if (options.onEdit) {
      options.onEdit(row, index);
    }
  }

  async function handlerFilterPresale(e: boolean) {
    filter.presale = e;
    pagination.currentPage = 1;
    await loadData();
  }

  async function handleFilterFlower(e: string[]) {
    filter.flower = e;
    pagination.currentPage = 1;
    await loadData();
  }

  onMounted(() => {
    loadData();
  });

  async function refresh() {
    await loadData();
  }

  async function reload() {
    pagination.currentPage = 1;
    await loadData();
  }

  async function search() {
    pagination.currentPage = 1;
    loadData();
  }

  return {
    loading,
    columns,
    dataList,
    pagination,
    loadingConfig,
    adaptiveConfig,
    filter,
    onSizeChange,
    onCurrentChange,
    refresh,
    reload,
    search
  };
}
